const express = require("express");
const cors = require("cors");
const userRouter = require("./router/user");
const userinfoRouter = require("./router/userinfo");
const app = express();
// 配置跨域  在路由之前
app.use(cors());
// 配置内置的解析post的请求数据中间件  解析表单数据的中间件
app.use(express.json());
app.use(express.urlencoded());
// 挂载路由
// 挂载用户登录注册路由
app.use("/api", userRouter);
// 先挂全局token中间件
// 引入解析token中间件
const expressJWT = require("express-jwt");
const config = require("./config");
app.use("/my", expressJWT({ secret: config.serectKey }));
// 挂载个人信息路由
app.use("/my", userinfoRouter);
// 挂载文章分类路由
const artCateRouter = require("./router/artcate");
app.use("/my/article", artCateRouter);
// 挂载文章路由
const articleRouter = require("./router/article");
app.use("/my/article", articleRouter);
// 托管upload中的文件为静态资源
app.use("/uploads", express.static("./uploads"));
const Joi = require("joi");
// 错误级别中间件
app.use(function (err, req, res, next) {
  //验证token是否有并且传递
  if (err.name === "UnauthorizedError") {
    return res.send({ status: 1, message: "身份认证失败" });
  }
  // Joi 参数校验失败
  if (err instanceof Joi.ValidationError) {
    return res.send({
      status: 1,
      message: err.message,
    });
  }
  // 未知错误
  res.send({
    status: 1,
    message: err.message,
  });
});
app.listen(3000, () => console.log("http://localhost:3000/"));
